package cmpe451.group7.ourcity.service.impl;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cmpe451.group7.ourcity.dao.BadgeDAO;
import cmpe451.group7.ourcity.dao.CommentDAO;
import cmpe451.group7.ourcity.dao.PlaceDAO;
import cmpe451.group7.ourcity.dao.TagDAO;
import cmpe451.group7.ourcity.dao.UserDAO;
import cmpe451.group7.ourcity.entity.Badge;
import cmpe451.group7.ourcity.entity.Comment;
import cmpe451.group7.ourcity.entity.Place;
import cmpe451.group7.ourcity.entity.Tag;
import cmpe451.group7.ourcity.entity.User;
import cmpe451.group7.ourcity.service.CommentService;

@Service("commentService")
public class CommentServiceImpl implements CommentService, Serializable {

	private static final long serialVersionUID = 1L;

	@Autowired
	private CommentDAO commentDAO;

	@Autowired
	private BadgeDAO badgeDAO;

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private TagDAO tagDAO;

	@Autowired
	private PlaceDAO placeDAO;

	@Override
	@Transactional
	public List<Comment> findComments(Place place) {
		List<Comment> comments = commentDAO.findPlaceComments(place);

		if (comments != null) {
			for (Comment c : comments) {
				commentDAO.initialize(c.getTags());
			}
		}

		return comments;
	}

	@Override
	@Transactional
	public Comment createComment(Place place, User user, String commentText,
			List<Tag> tags, Date date) {

		List<Comment> comments = commentDAO.findUserComments(user.getUserID());

		List<Badge> commentBadges = badgeDAO.getCommentBadges();

		Set<Badge> userBadges = user.getBadges();
		for (int i = 0; i < commentBadges.size(); i++) {
			if (comments.size() + 1 == commentBadges.get(i).getBadgeCount()) {
				if (!userBadges.contains(commentBadges.get(i))) {
					userBadges.add(commentBadges.get(i));
				}
			}
		}

		userDAO.merge(user);

		if (CollectionUtils.isNotEmpty(tags)) {
			for (Tag t : tags) {
				tagDAO.saveIfNotExists(t);
			}
		}

		return commentDAO.createComment(place, user, commentText, tags, date);
	}

	@Override
	@Transactional
	public List<Comment> findByRestrictions(long placeID, String comment,
			Date fromDate, Date toDate, List<Tag> tags) {

		List<Comment> comments = commentDAO.findByRestrictions(placeID,
				comment, fromDate, toDate, tags);

		if (comments != null) {
			for (Comment c : comments) {
				commentDAO.initialize(c.getTags());
			}
		}

		return comments;
	}

}
